<?php

class ServiceController extends Controller {

    /**
     * @param string the symbol of the stock
     * @param string
     * @param string the price will be return (low, high, open,...)
     * @return float the stock price
     */
    public function getLatestPrices($ticker, $date, $type) {
        $company = Company::model()->findAll("ticket = :ticket", array(":ticket" => $ticker));
        if (count($company) == 0) {
            return -1; //Unknown Ticker
        }
        $date = Stock::uk_date_to_mysql_date($date);
        $stock = Stock::model()->findAll("companyID = :comID and timestamp = :date", array(":comID" => $company[0]->id, ":date" => $date));
        if (count($stock) == 0) {
            return -2; //No data or Wrong date format
        } else {
            switch ($type) {
                case "low":
                    return $stock[0]->low;
                case "high":
                    return $stock[0]->high;
                case "close":
                    return $stock[0]->close;
                case "open":
                    return $stock[0]->open;
                case "avg":
                    return $stock[0]->avg;
                case "ref":
                    return $stock[0]->ref;
                case "ceiling":
                    return $stock[0]->ceiling;
                case "floor":
                    return $stock[0]->floor;
                case "volumeagreement":
                    return $stock[0]->volumeAgreement;
                case "matchedvolume":
                    return $stock[0]->volumeKhopLenh;
                case "valueagreement":
                    return $stock[0]->valueAgreement;
                case "matchedvalue":
                    return $stock[0]->valueKhopLenh;
                default :
                    return -3; //Wrong price type
            }
        }
    }

    public function actionGetPrices() {
        if (isset($_REQUEST['ticker']) && isset($_REQUEST['date']) && isset($_REQUEST['type'])) {
            $ticker = strtoupper($_REQUEST['ticker']);
            $type = strtolower($_REQUEST['type']);
            $date = $_REQUEST['date'];

            echo $this->getLatestPrices($ticker, $date, $type);
        }
    }

}